import React, { memo, useEffect, useRef } from 'react';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import { connect } from 'react-redux';
require('codemirror/lib/codemirror.css');
require('codemirror/theme/material.css');
require('codemirror/theme/monokai.css');
// require('codemirror/theme/');
require('codemirror/mode/xml/xml.js');
require('codemirror/mode/javascript/javascript.js');
import './index.less';
function CodePanel(props: API.ICodePanel) {
  const {
    project: { codes, project, currentPage, mode },
    asyncPageCode,
    saveCode,
  } = props;
  const currentPageName: string = currentPage.split('.')[0];
  const currentPageCode: string = codes[currentPageName] || '';
  const ref: React.LegacyRef<any> = useRef();
  function handleChange(e) {
    // console.log('代码变化');
    // console.log(e.doc.getValue());
    // 保存代码
  }

  useEffect(() => {
    const editor = ref?.current?.shared.editor;
    editor.setSize('100%', '100%');
  }, []);

  useEffect(() => {
    const editor = ref?.current?.shared.editor;
    editor.setValue(currentPageCode);
  }, [currentPageCode, mode]);

  return (
    <div className="editBox" style={props.style}>
      <CodeMirror
        ref={ref}
        className="editor"
        value={currentPageCode}
        options={{
          mode: { name: 'text/javascript' },
          theme: 'monokai',
          lineNumbers: true,
          //start-设置支持代码折叠
          lineWrapping: true,
          foldGutter: true,
          gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
          matchBrackets: true, //括号匹配，光标旁边的括号都高亮显示
          autoCloseBrackets: true, //键入时将自动关闭()[]{}''""
          extraKeys: {
            'Alt-/': 'autocomplete',
            'Ctrl-S': function (editor: any) {
              const code = editor.getValue();
              saveCode({code} as any);

              asyncPageCode({
                code: editor.getValue(),
                project,
                page: currentPage,
              });
            },
            'Ctrl-Z': function (editor: any) {
              editor.undo();
            }, //undo
            F8: function (editor: any) {
              editor.redo();
            }, //Redo
          },
        }}
        onChange={handleChange}
      />
    </div>
  );
}

export default connect(({ project }: any) => ({ project }), {
  asyncPageCode: (payload: { code: string }) => ({
    type: 'project/asyncPageCode',
    payload,
  }),
  saveCode: (payload: { code: string }) => ({
    type: 'project/saveCode',
    payload,
  }),
})(memo(CodePanel));
